package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.feign.ArticleApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.service.ApUserRealnameService;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>APP实名认证信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ArticleApAuthorFeign articleApAuthorFeign;

    /**
     * APP实名认证信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo pageList(ApUserRealnamePageRequestDto dto) {

        //构建分页参数
        IPage<ApUserRealname> iPage = new Page<>(dto.getPage(), dto.getSize());
        //构建查询条件对象
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());
        //执行查询
        page(iPage, queryWrapper);
        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 实名认证驳回
     *
     * @param map
     */
    @Override
    public void authFail(Map<String, Object> map) {
        //获得请求参数
        Integer id = (Integer) map.get("id");
        String msg = (String) map.get("msg");
        //对请求参数进行判断
        if (null == id || null == msg) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        //根据id查询ApUserRealname对象(唯一)
        //ApUserRealname apUserRealname = query().eq("id", id).one();
        //如果利用spring plus 可以不用查询了
        ApUserRealname apUserRealname = new ApUserRealname();
        //设置对象的审核状态为2，审核原因reason，以及更新时间
        apUserRealname.setId(id.longValue());
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        apUserRealname.setReason(msg);
        apUserRealname.setUpdatedTime(LocalDateTime.now());
        //更新对象
        updateById(apUserRealname);
    }

    /**
     * 实名认证通过
     *
     * @param map
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void authPass(Map<String, Object> map) {
        //获得请求参数
        Integer id = (Integer) map.get("id");

        //对请求参数进行判断
        if (null == id) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        //根据id查询ApUserRealname对象(唯一)
        //ApUserRealname apUserRealname = query().eq("id", id).one();
        ApUserRealname apUserRealname = getById(id);

        //获得用户id
        Long apUserId = Long.valueOf(apUserRealname.getUserId());
        //查询apUser对象
        ApUser apUser = apUserMapper.selectById(apUserId);

        //远程调用创建自媒体账号
        Long wmUserId = addWmUser(apUser);
        //远程调用创建作者
        addApAuthor(apUser, wmUserId);
        //更新实名认证信息
        updateApUserRealname(id);
        //更新用户的实名认证状态
        updateApUserStatus(apUserId);

    }

    //更新用户的实名认证状态
    private void updateApUserStatus(Long apUserId) {
        //创建ApUser对象，并设置 is_identity_authentication为1 ，flag为1
        ApUser upApUser = new ApUser();
        upApUser.setId(apUserId);
        upApUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        upApUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        apUserMapper.updateById(upApUser);
    }

    //更新实名认证信息
    private void updateApUserRealname(Integer id) {
        ApUserRealname upApUserRealname = new ApUserRealname();
        //设置对象的审核状态为9，以及更新时间
        upApUserRealname.setId(id.longValue());
        upApUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        upApUserRealname.setUpdatedTime(LocalDateTime.now());
        //更新对象
        updateById(upApUserRealname);
    }

    //远程调用添加作者账号
    private void addApAuthor(ApUser apUser, Long wmUserId) {
        //先查询作者信息是否存在
        ResultVo<ApAuthor> resultAuthor = articleApAuthorFeign.getByApUserIdWmUserId(apUser.getId(), wmUserId);
        if (!resultAuthor.isSuccess()) {
            log.error("远程调用作者微服务查询作者账号信息失败了，失败id：" + apUser.getId() + "wmUserId:" + wmUserId);
            throw new LeadNewsException("远程调用作者微服务查询作者账号信息失败了");
        }
        ApAuthor apAuthor = resultAuthor.getData();
        //如果不存在就添加作者信息
        if (null == apAuthor) {
            apAuthor = new ApAuthor();
            apAuthor.setName(apUser.getName());
            apAuthor.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            apAuthor.setUserId(apUser.getId());
            apAuthor.setCreatedTime(LocalDateTime.now());
            apAuthor.setWmUserId(wmUserId);
            ResultVo<ApAuthor> authorResultVo = articleApAuthorFeign.add(apAuthor);
            if (!authorResultVo.isSuccess()) {
                log.error("远程调用作者微服务添加作者账号信息失败了，失败id：" + apUser.getId() + "wmUserId:" + wmUserId);
                throw new LeadNewsException("远程调用作者微服务添加作者账号信息失败了");
            }
        }


    }

    //远程调用添加自媒体账号
    private Long addWmUser(ApUser apUser) {
        //先查询自媒体信息是否存在
        ResultVo<WmUser> resultWmUser = wmUserFeign.getByApUserId(apUser.getId());
        //如果远程调用不成功就抛异常，让事务回滚
        if (!resultWmUser.isSuccess()) {
            log.error("远程调用自媒体微服务查询自媒体账号信息失败了，失败id：" + apUser.getId());
            throw new LeadNewsException("远程调用自媒体微服务查询自媒体账号信息失败了");
        }
        WmUser wmUser = resultWmUser.getData();
        if (null == wmUser) {
            //如果不存在就添加自媒体信息
            wmUser = new WmUser();
            //先将apUser拷贝到wmUser中：注意，不要将apUser的id变成wmUser的主键id
            BeanUtils.copyProperties(apUser, wmUser);
            wmUser.setId(null);
            wmUser.setApUserId(apUser.getId());
            wmUser.setNickname(apUser.getName());
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setScore(0);
            wmUser.setCreatedTime(LocalDateTime.now());
            ResultVo<WmUser> resultVo = wmUserFeign.add(wmUser);
            if (!resultVo.isSuccess()) {
                log.error("远程调用自媒体微服务添加自媒体账号信息失败了，失败id：" + apUser.getId());
                throw new LeadNewsException("远程调用自媒体微服务添加自媒体账号信息失败了");
            }
            wmUser = resultVo.getData();
        }

        //返回添加的自媒体的id
        return wmUser.getId();
    }
}